package com.hingstd.lastwork.controllers;

import com.hingstd.lastwork.dao.ArticleRepository;
import com.hingstd.lastwork.dao.UserAccountRepository;
import com.hingstd.lastwork.entities.Article;
import com.hingstd.lastwork.entities.UserAccount;
import com.hingstd.lastwork.services.ArticleService;
import com.hingstd.lastwork.services.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("articles")
public class ArticleController {

    @Autowired
    ArticleService articleService;

    @Autowired
    UserAccountService userAccountService;

    @GetMapping("/new")
    public String displayArticleForm(Model model){

        Article aArticle = new Article();
        List<UserAccount> userAccounts = userAccountService.getAll();
        model.addAttribute("article", aArticle);
        model.addAttribute("allUserAccounts",userAccounts);
        return "new-article";
    }

    @PostMapping("/save")
    public String createArticle(Model model, @RequestParam List<Long> userAccounts, Article article){
        //处理保存数据库
        articleService.save(article);
//        Iterable<UserAccount> chosenUserAccounts = userAccountRepository.findAllById(userAccounts);
//        for (UserAccount userAccount : chosenUserAccounts){
//            userAccount.setArticle(article);
//            userAccountRepository.save(userAccount);
//        }
        return "redirect:/articles/new";
    }
}
